<template>
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" inline label-width="68px">
      <el-form-item label="序列号" prop="serialNumber">
        <el-input v-model="queryParams.serialNumber" placeholder="请输入序列号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="柜机别名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入柜机别名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="所属门店" prop="storeId">
        <el-select v-model="queryParams.storeId" placeholder="请选择门店">
          <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="授权状态" prop="authorize">
        <el-select v-model="queryParams.authorize" placeholder="请选择">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['mc:cabinet:add']" type="primary" plain icon="el-icon-plus" size="mini"
          @click="handleAdd">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['mc:cabinet:remove']" type="danger" plain icon="el-icon-delete" size="mini"
          :disabled="multiple" @click="handleDelete">
          删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="cabinetList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="80" align="center" />
      <el-table-column label="序列号" align="center" prop="serialNumber" />
      <el-table-column label="柜机别名" align="center" prop="name" />
      <el-table-column label="所属门店" align="center" prop="storeId">
        <template slot-scope="scope">
          {{getStore(scope.row.storeId)}}
        </template>
      </el-table-column>
      <el-table-column label="型号" align="center" prop="model">
        <template slot-scope="scope">
          <span>{{ scope.row.model == 0 ? '未知' : scope.row.model == 2 ? '两组药架' : scope.row.model == 4 ? '四组药架' :
            scope.row.model == 6 ? '六组药架' : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="授权" align="center" prop="authorize" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.authorize == 0 ? '正常' : '冻结' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="密码" align="center" prop="password" /> -->
      <el-table-column label="柜机状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ scope.row.status == 1 ? '待交付' : scope.row.status == 2 ? '已交付' : scope.row.status == 3 ? '已回收' :
            scope.row.status == 4 ? '其他' : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产日期" align="center" prop="manufactureTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.manufactureTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="交付时间" align="center" prop="deliveryTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="回收时间" align="center" prop="recycleTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recycleTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="280">
        <template slot-scope="scope">
          <el-button v-hasPermi="['mc:cabinet:edit']" size="mini" type="text" icon="el-icon-setting"
            @click="handleThreshold(scope.row)">
            温湿度阈值
          </el-button>
          <el-button v-if="scope.row.status == 3" v-hasPermi="['mc:cabinet:edit']" size="mini" type="text"
            icon="el-icon-edit" @click="handleUpdate(scope.row)">
            修改
          </el-button>
          <el-button v-hasPermi="['mc:cabinet:remove']" size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改柜机信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="6.5">
            <el-form-item label="序列号" prop="serialNumber">
              <el-input v-model="form.serialNumber" placeholder="请输入序列号" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.id" :span="1.5" class="mt5">
            <el-button type="primary" icon="el-icon-refresh" size="mini" @click="handleUpdate(form)">
              刷新
            </el-button>
          </el-col>
          <el-col :span="7">
            <el-form-item label="门店" prop="storeId">
              <el-select v-model="form.storeId" placeholder="请选择门店">
                <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="7">
            <el-form-item label="柜机别名" prop="name">
              <el-input v-model="form.name" placeholder="请输入柜机别名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="型号" prop="model">
              <el-select v-model="form.model" placeholder="请选择">
                <el-option v-for="item in modelOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="授权" prop="authorize">
              <el-select v-model="form.authorize" placeholder="请选择">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5.5">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入密码" show-password />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产日期" prop="manufactureTime">
              <el-date-picker clearable v-model="form.manufactureTime" type="date" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择生产日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <div v-if="form.model > 0" class="cabinet-images">
          <div class="bg-top">反面</div>
          <div class="bg">
            <div class="bg-left">前门显示器方向</div>
            <div class="bg-con">
              <el-row :class="['cabinet-row', `model-${form.model}`]">
                <el-col :span="getColSpan" v-for="index in form.model" :key="index">
                  <div class="image-box">
                    <div class="image-title">

                      <span class="image-title-text" v-for="(i,j) in groupArr"
                        v-if="j == index-1">{{i}}组{{form.model>=index *2?'(反面)':'(正面)'}}</span>
                      <span class="mr">
                        <el-select v-model="mesInfo['shelf' + index + 'Group']" class="shelf-header-select" size="mini">
                          <el-option v-for="item in groupArr" :key="item.value" :label="`${item}组`" :value="item" />
                        </el-select>
                      </span>
                      <span class="mr">
                        <el-input v-model="mesInfo['shelf' + index + 'Value3']" class="shelf-header-value"
                          size="mini" />
                      </span>
                      <span class="mr">
                        <el-button type="success" size="mini"
                          @click="handleDeal(mesInfo['shelf' + index + 'Value3'], index)">
                          应用
                        </el-button>
                      </span>
                    </div>
                    <div class="shelf-header">
                      <div class="shelf-header-item">
                        <span class="shelf-header-value disabled">
                          {{selectedGroup==0?parseInt(mesInfo['shelf' + index +'Value3'])+1:(index == selectedGroup?
                          parseInt(currentData)+1
                          :parseInt(mesInfo['shelf' +index +'Value3']) )}}
                        </span>
                      </div>
                      <div class="shelf-header-item">
                        <el-input v-model="mesInfo['shelf' + index + 'Value1']" class="shelf-header-value2"
                          type="number" min="0"
                          @input="(val) => validateInput(val, 'shelf' + index + 'Value1', 'height')" size="mini" />
                      </div>
                      <div class="shelf-header-item">
                        <el-select v-model="mesInfo['shelf' + index + 'Size']" class="shelf-header-select" size="mini">
                          <el-option v-for="item in dict.type.slots_spacing_option" :key="item.value"
                            :label="item.label" :value="Number(item.value)" />
                        </el-select>
                      </div>
                      <div class="shelf-header-item">
                        <el-input v-model="mesInfo['shelf' + index + 'Value2']" class="shelf-header-value" type="number"
                          min="0" @input="(val) => validateInput(val, 'shelf' + index + 'Value2', 'slots')"
                          size="mini" />
                      </div>
                      <div class="shelf-header-item">
                        <el-button type="primary" size="mini"
                          @click="handleAddShelf(mesInfo['shelf' + index + 'Value1'],mesInfo['shelf' + index + 'Size'],mesInfo['shelf' + index + 'Value2'],index)">
                          添加
                        </el-button>
                      </div>
                    </div>
                    <div class="shelf-contain">
                      <shelf-table :ref="`shelfTable${index}`" :initial-data="getShelfData(index)"
                        :groupLength="mesInfo['shelf' + index + 'Value3']" :group-no="index" :model="form.model"
                        :spacing-option="dict.type.slots_spacing_option" @update:data="handleShelfDataUpdate" />
                    </div>
                  </div>
                  <div class="middle-title" v-if="form.model>=index *2" :class="{
                      'model-2-9': form.model == 2&& currIndex < 2,
                      'model-2-19': form.model == 2&& currIndex == 2,
                      'model-2-29': form.model == 2&& currIndex > 2,
                      'model-other-9': form.model != 2&& currIndex < 2,
                      'model-other-19': form.model != 2 && currIndex == 2,
                      'model-other-29': form.model != 2 && currIndex > 2,
                    }">
                    机械臂通道
                  </div>
                </el-col>
              </el-row>
            </div>
            <div class="bg-left">后门方向</div>
          </div>
          <div class="bg-top">正面</div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <Sensor-dialog v-model="thresholdShow" :form="thresholdFrom" @close="closeSensor" />
  </div>
</template>

<script>
  import {
    listCabinet,
    getCabinetDetail,
    delCabinet,
    addCabinet,
    updateCabinet,
  } from "@/api/mc/cabinet";
  import { listStore } from "@/api/mc/store";
  import ShelfTable from './components/shelf-table.vue';
  import SensorDialog from './components/SensorDialog.vue';
  export default {
    name: "Cabinet",
    dicts: [
      "slots_spacing_option",
    ],
    components: {
      ShelfTable,
      SensorDialog
    },
    data() {
      return {
        options: [{
          value: 0,
          label: '正常'
        }, {
          value: 1,
          label: '冻结'
        }],
        modelOptions: [{
          value: 0,
          label: '未知'
        }, {
          value: 2,
          label: '两组药架'
        }, {
          value: 4,
          label: '四组药架'
        }, {
          value: 6,
          label: '六组药架'
        }],
        value: '',
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 柜机信息表格数据
        cabinetList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          storeId: null,
          serialNumber: null,
          name: null,
          model: null,
          authorize: null,
          password: null,
          manufactureTime: null,
        },
        // 表单参数
        form: {},
        mesInfo: {},
        // 表单校验
        rules: {
          serialNumber: [
            { required: true, message: '序列号不能为空', trigger: 'blur' },
            { pattern: /^[a-zA-Z0-9]+$/, message: '只能输入字母和数字', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '柜机别名不能为空', trigger: 'blur' }
          ],
          model: [
            { required: true, message: '请选择型号', trigger: 'change' }
          ],
          authorize: [
            { required: true, message: '请选择授权状态', trigger: 'change' }
          ],
          password: [
            { required: true, message: '密码不能为空', trigger: 'blur' }
          ],
          manufactureTime: [
            { required: true, message: '请选择生产日期', trigger: 'change' }
          ],
          storeId: [
            { required: true, message: '请选择门店', trigger: 'change' }
          ]
        },
        // 药架层数据
        shelfData: {},
        groupArr: [],
        storeList: [],
        isSubmitting: false, // 添加提交状态标记
        thresholdShow: false, // 阈值设置
        thresholdFrom: {}, // 阈值设置表单
        selectedGroup: 0,
        currentData: 1,
        currIndex: 1
      };
    },
    created() {
      this.getList();
      this.getStoreList();
    },
    computed: {
      getColSpan() {
        // 根据型号返回不同的列宽
        switch (this.form.model) {
          case 2:
            return 24; // 上下排列，每个占满宽度
          case 4:
            return 12; // 田字格排列，每个占1/2宽度
          case 6:
            return 8; // 3*2排列，每个占1/3宽度
          default:
            return 8;
        }
      }
    },
    watch: {
      'form.model': {
        immediate: true,
        handler(newVal) {
          if (newVal) {
            this.getGroup(newVal);
            this.currentData = 1
          }
        }
      }
    },
    methods: {
      // 获取门店列表
      getStoreList() {
        listStore({ pageNum: 1, pageSize: 1000 }).then((res) => {
          this.storeList = res.rows;
        });
      },
      handleDeal(res, index) {
        // 获取当前选择的组
        const selectedGroup = this.mesInfo[`shelf${index}Group`];
        // 获取目标行数
        const targetRows = parseInt(res) || 0;

        // 获取目标组的当前数据
        const currentData = this.shelfData[selectedGroup] || [];

        // 如果目标行数大于当前行数，添加新行
        if (targetRows > currentData.length) {
          const newRows = targetRows - currentData.length;
          for (let i = 0; i < newRows; i++) {
            currentData.unshift({
              height: parseInt(this.mesInfo[`shelf${index}Value1`]) || 84,
              space: parseInt(this.mesInfo[`shelf${index}Size`]) || 100,
              slots: parseInt(this.mesInfo[`shelf${index}Value2`]) || 9,
              groupName: selectedGroup,
              layer: currentData.length + 1
            });
          }
        }
        // 如果目标行数小于当前行数，删除多余行
        else if (targetRows < currentData.length) {
          const rowsToRemove = currentData.length - targetRows;
          currentData.splice(0, rowsToRemove);
        }

        // 确保数据中的层号是正确的倒序排列
        currentData.forEach((item, idx) => {
          item.layer = currentData.length - idx;
        });

        // 更新 shelfData
        this.$set(this.shelfData, selectedGroup, currentData);
        this.selectedGroup = this.groupArr.findIndex((item => item == selectedGroup)) + 1
        this.currentData = currentData.length
        if (index <= 3) {
          this.currIndex = Math.floor(currentData.length / 9)
        }
        console.log(index, '=======---', currentData.length)
        // 更新显示的行数
        this.$set(this.mesInfo, `shelf${index}Value3`, currentData.length);
      },
      getGroup(model) {
        // 保存当前数据
        const currentData = { ...this.shelfData };

        // 根据新型号设置组别
        if (model == 2) {
          this.groupArr = ['B', 'A'];
        } else if (model == 4) {
          this.groupArr = ['D', 'B', 'C', 'A'];
        } else if (model == 6) {
          this.groupArr = ['F', 'D', 'B', 'E', 'C', 'A'];
        }

        // 重置shelfData
        this.shelfData = {};

        // 重新映射数据
        this.groupArr.forEach((group, index) => {
          // 直接使用当前组的数据
          if (currentData[group]) {
            this.$set(this.shelfData, group, currentData[group]);
          } else {
            // 如果没有数据，创建默认数据
            const defaultData = Array(9).fill().map((_, i) => ({
              height: parseInt(this.mesInfo[`shelf${index + 1}Value1`]) || 84,
              space: parseInt(this.mesInfo[`shelf${index + 1}Size`]) || 100,
              slots: parseInt(this.mesInfo[`shelf${index + 1}Value2`]) || 9,
              groupName: group,
              layer: 9 - i
            }));
            this.$set(this.shelfData, group, defaultData);
          }
        });

        // 更新mesInfo中的组别信息
        this.groupArr.forEach((group, index) => {
          this.$set(this.mesInfo, `shelf${index + 1}Group`, group);
        });

        // 重置layerGroups数组
        this.form.layerGroups = [];
        // 根据当前型号初始化对应数量的组
        this.groupArr.forEach(groupName => {
          this.form.layerGroups.push({
            layers: this.shelfData[groupName] || [],
            groupName: groupName
          });
        });
      },
      handleAddShelf(a, b, c, index) {
        // 验证输入值是否合法
        const layerHeight = parseInt(a);
        const slotCount = parseInt(c);

        if (isNaN(layerHeight) || layerHeight <= 0) {
          this.$message.error('层高必须大于0');
          return;
        }

        if (isNaN(slotCount) || slotCount <= 0) {
          this.$message.error('槽数必须大于0');
          return;
        }

        const refName = `shelfTable${index}`
        if (this.$refs[refName] && this.$refs[refName][0]) {
          this.$refs[refName][0].addRow(layerHeight.toString(), b, slotCount.toString())

          // 获取当前组的数据
          const selectedGroup = this.mesInfo[`shelf${index}Group`];
          const currentData = this.shelfData[selectedGroup] || [];

          // 更新 disabled 盒子的值为层数+1
          this.$set(this.mesInfo, `shelf${index}Value3`, currentData.length);
        }
      },
      /** 查询柜机信息列表 */
      getList() {
        this.loading = true;
        listCabinet(this.queryParams)
          .then((res) => {
            this.cabinetList = res.rows;
            this.total = res.total;
          })
          .finally(() => {
            this.loading = false;
          });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.mesInfo = {
          // 添加药架相关字段
          shelf1Value1: '84',
          shelf1Value2: '9',
          shelf1Value3: '9',
          shelf1Group: 'F',
          shelf1Size: '100',
          shelf2Value1: '84',
          shelf2Value2: '9',
          shelf2Value3: '9',
          shelf2Group: 'F',
          shelf2Size: '100',
          shelf3Value1: '84',
          shelf3Value2: '9',
          shelf3Value3: '9',
          shelf3Group: 'F',
          shelf3Size: '100',
          shelf4Value1: '84',
          shelf4Value2: '9',
          shelf4Value3: '9',
          shelf4Group: 'F',
          shelf4Size: '100',
          shelf5Value1: '84',
          shelf5Value2: '9',
          shelf5Value3: '9',
          shelf5Group: 'F',
          shelf5Size: '100',
          shelf6Value1: '84',
          shelf6Value2: '9',
          shelf6Value3: '9',
          shelf6Group: 'F',
          shelf6Size: '100',
        }
        this.form = {
          id: null,
          storeId: null,
          serialNumber: null,
          name: null,
          model: null,
          authorize: null,
          password: null,
          manufactureTime: null,
          layerGroups: []
        };
        // 清空药架数据
        this.shelfData = {};
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {

        this.reset();
        this.form.authorize = 0;
        this.open = true;
        this.title = "添加柜机信息";
      },
      getStore(id) {
        const store = this.storeList.find((item) => item.id == id);
        return store ? store.name : '';
      },
      // 温湿度阈值配置
      handleThreshold(row) {
        this.thresholdFrom = Object.assign({}, row);
        this.thresholdShow = true;
      },
      // 关闭温湿度传感器阈值配置窗口
      closeSensor() {
        this.thresholdFrom = {}; // 清空表单
        this.handleQuery(); // 刷新列表
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.selectedGroup = 0
        this.reset();
        getCabinetDetail(row.id).then((res) => {
          this.form = res.data;

          // 处理型号为未知的情况
          if (res.data.model === 0) {
            this.$set(this.form, 'model', 0);
            this.groupArr = [];
            this.shelfData = {};
            this.open = true;
            this.title = "修改柜机信息";
            return;
          }

          // 先设置型号，触发getGroup方法初始化groupArr
          this.$set(this.form, 'model', res.data.model);

          // 处理每个组的数据
          if (res.data.layerGroups && res.data.layerGroups.length > 0) {
            // 初始化 shelfData
            this.shelfData = {};

            // 处理接口返回的数据
            res.data.layerGroups.forEach(group => {
              if (group.layers && group.layers.length > 0) {
                // 直接使用组名作为键存储数据
                this.shelfData[group.groupName] = group.layers;
                // 找到对应的索引
                setTimeout(() => {
                  const index = this.groupArr.indexOf(group.groupName) + 1;
                  if (index > 0) {
                    this.$set(this.mesInfo, `shelf${index}Value3`, group.layers.length);
                    // 更新其他相关值
                    const firstLayer = group.layers[0];
                    this.$set(this.mesInfo, `shelf${index}Value1`, firstLayer.height || 84);
                    this.$set(this.mesInfo, `shelf${index}Value2`, firstLayer.slots || 9);
                    this.$set(this.mesInfo, `shelf${index}Size`, firstLayer.space || 100);
                    this.$set(this.mesInfo, `shelf${index}Group`, group.groupName);
                  }
                }, 100)
              }
            });

            // 初始化没有数据的组
            this.groupArr.forEach((groupName, index) => {
              if (!this.shelfData[groupName]) {
                const defaultData = Array(9).fill().map((_, i) => ({
                  height: parseInt(this.mesInfo[`shelf${index + 1}Value1`]) || 84,
                  space: parseInt(this.mesInfo[`shelf${index + 1}Size`]) || 100,
                  slots: parseInt(this.mesInfo[`shelf${index + 1}Value2`]) || 9,
                  groupName: groupName,
                  layer: 9 - i
                }));
                this.shelfData[groupName] = defaultData;
                this.$set(this.mesInfo, `shelf${index + 1}Value3`, 9);
              }
            });
            // console.log(res.data.layerGroups, '-----shelfData')

            this.open = true;
            this.title = "修改柜机信息";

          }
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.isSubmitting) return;
            this.isSubmitting = true;
            if (this.form.id != null) {
              this.$modal.confirm('该操作会清空坐标数据，请谨慎处理，是否确认修改？').then(() => {
                updateCabinet(this.form).then((res) => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }).finally(() => {
                  this.isSubmitting = false;
                });
                }).catch(() => {});
            } else {
              addCabinet(this.form).then((res) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.isSubmitting = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal
          .confirm('是否确认删除该柜机？')
          .then(() => {
            delCabinet(ids).then(() => {
              this.getList();
              this.$modal.msgSuccess("删除成功");
            });
          })
          .catch(() => { });
      },
      // 获取药架层数据
      getShelfData(groupNo) {
        const groupName = this.groupArr[groupNo - 1];

        // 如果该组没有数据，初始化默认数据
        if (!this.shelfData[groupName] || this.shelfData[groupName].length === 0) {
          const defaultData = Array(9).fill().map((_, index) => ({
            height: parseInt(this.mesInfo[`shelf${groupNo}Value1`]) || 84,
            space: parseInt(this.mesInfo[`shelf${groupNo}Size`]) || 100,
            slots: parseInt(this.mesInfo[`shelf${groupNo}Value2`]) || 9,
            groupName: groupName,
            layer: 9 - index
          }));
          this.$set(this.shelfData, groupName, defaultData);
        }

        // 确保数据中的层号是正确的倒序排列
        const currentData = this.shelfData[groupName];
        if (currentData) {
          currentData.forEach((item, index) => {
            item.layer = currentData.length - index;
          });
        }

        return this.shelfData[groupName] || [];
      },
      // 处理药架层数据更新
      handleShelfDataUpdate({ groupNo, data }) {
        const groupName = this.groupArr[groupNo - 1];
        this.shelfData[groupName] = data;

        if (data && data.length > 0) {
          // 更新对应组的数据
          const existingGroupIndex = this.form.layerGroups.findIndex(
            group => group.groupName === groupName
          );

          if (existingGroupIndex !== -1) {
            this.form.layerGroups[existingGroupIndex].layers = data;
          } else {
            this.form.layerGroups.push({
              layers: data,
              groupName: groupName
            });
          }
        }
      },
      validateInput(value, field, type) {
        // 如果输入为空，重置为空字符串
        if (value === '') {
          this.$set(this.mesInfo, field, '');
          return;
        }

        // 转换为数字并验证
        const numValue = parseFloat(value);

        // 检查是否为非数字
        if (isNaN(numValue)) {
          this.$set(this.mesInfo, field, '');
          this.$message.error(`请输入有效的数字`);
          return;
        }

        // 检查是否为负数
        if (numValue < 0) {
          this.$set(this.mesInfo, field, '');
          this.$message.error(`${type === 'height' ? '层高' : '槽数'}不能为负数`);
          return;
        }

        // 检查是否为整数
        if (!Number.isInteger(numValue)) {
          this.$set(this.mesInfo, field, '');
          this.$message.error(`${type === 'height' ? '层高' : '槽数'}必须是整数`);
          return;
        }

        // 设置有效值
        this.$set(this.mesInfo, field, numValue);
      },
    },
  };
</script>
<style scoped>
  .cabinet-images {
    padding: 10px;
    background: #5F9EA0;
  }

  .cabinet-row {
    display: flex;
    flex-wrap: wrap;
  }

  .bg {
    display: flex;
    align-items: center;
  }

  .bg-con {
    width: 98%;
    background: #C0C0C0;
    border: 4px solid #808080;
    position: relative;
  }

  .bg-left {
    width: 3%;
    color: #fff;
    text-align: center;
    font-size: 22px;
    font-weight: bold;
  }

  .bg-top {
    text-align: center;
    width: 100%;
    height: 40px;
    line-height: 40px;
    color: #fff;
    font-size: 20px;
    font-weight: bold;
  }

  .image-box {
    text-align: center;
    border: 2px solid #808080;
    margin-bottom: 30px;
    background: #5F9EA0;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    position: relative;
  }

  .image-title {
    font-size: 16px;
    color: #fff;
    font-weight: bold;
    padding: 5px 0 3px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .image-title-text {
    margin-right: 10px;
    text-align: center;
    width: 60%;
  }

  .mr {
    margin-right: 4px;
  }

  .shelf-header {
    display: flex;
    justify-content: space-between;
    padding: 0px 1px 4px;
    border-radius: 4px;
  }

  .shelf-header-item {
    display: flex;
    align-items: center;
    margin: 0 2px;
    flex: 1;
  }

  .shelf-header-value {
    width: 100%;
  }

  .shelf-header-value2 {
    width: 100%;
  }

  ::v-deep .el-input--mini .el-input__inner {
    height: 24px !important;
    line-height: 24px !important;
  }

  .shelf-header-value.disabled {
    color: #909399;
    background-color: #F5F7FA;
    border: 1px solid #E4E7ED;
    padding: 2px 8px;
    border-radius: 4px;
    width: 100%;
  }

  .shelf-header-select {
    width: 100%;
  }

  .middle-title {
    margin-bottom: 10px;
    font-size: 19px;
    position: absolute;
    top: 96.6%;
    min-height: 60px;
    line-height: 60px;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #fff;
    width: 100%;
    text-align: center;
    z-index: 1;
    pointer-events: none;

    &.model-2-9 {
      top: 98.5%;
    }

    &.model-2-19 {
      top: 99.5%;
    }

    &.model-2-29 {
      top: 99.8%;
    }

    &.model-other-9 {
      top: 97%;
    }

    &.model-other-19 {
      top: 98.2%;
    }

    &.model-other-29 {
      top: 98.8%;
    }
  }

  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 200px;
    background: #fafafa;
    color: #909399;
    font-size: 30px;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
  }

  .shelf-contain {
    width: 100%;
    height: 100%;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  /* 针对不同型号的特殊样式 */
  .model-2 .el-col,
  .model-4 .el-col,
  .model-6 .el-col {
    margin: 0 auto;
    position: relative;
  }

  .model-2 .el-col {
    margin-bottom: 20px;
  }

  /* 针对不同型号的表头样式 */
  .model-2 .shelf-header-item,
  .model-4 .shelf-header-item {
    flex: 1;
    margin: 0 2.5px;
  }

  .model-6 .shelf-header-item {
    flex: 0 0 auto;
  }

  /* 图片标题文本宽度 */
  .model-2 .image-title-text {
    width: 212%;
  }

  .model-4 .image-title-text {
    width: 61%;
  }

  /* 禁用状态的值宽度 */
  .model-2 .shelf-header-value.disabled {
    width: 936px;
  }

  .model-4 .shelf-header-value.disabled {
    width: 308px;
  }

  .model-6 .shelf-header-value.disabled {
    width: 100px;
  }

  /* 选择器和输入框宽度 */
  .model-2 .shelf-header-select,
  .model-4 .shelf-header-select {
    width: 95px;
  }

  .model-6 .shelf-header-select {
    width: 98px;
  }

  .model-4 .shelf-header-value,
  .model-6 .shelf-header-value {
    width: 62px;
  }

  .model-2 .shelf-header-value2,
  .model-4 .shelf-header-value2,
  .model-6 .shelf-header-value2 {
    width: 74px;
  }

  /* 底部边距处理 */
  .model-2 .el-col:last-child .image-box,
  .model-4 .el-col:nth-child(n+3) .image-box,
  .model-6 .el-col:nth-child(n+4) .image-box {
    margin-bottom: 0 !important;
  }
</style>